<?php session_start();?>
<!DOCTYPE html>
<html>
<head> 
<title> login </title>
<meta charset="UTF-8">
</head>

   <body>
      <!--the following script creates a connection to database and checks for valid password and username -->
      <?php
	
	if ($_SERVER["REQUEST_METHOD"] == "POST"){

	 $uname =$_POST['username']; //variable for posted username
	 $passw =$_POST['password']; // variable for posted password
        

      	// create a connection to mysql database
        $host= "localhost";
        $user = "root";
        $password = "password";
        $database = "PROJECT";
         
        
        $con=mysqli_connect($host,$user,$password,$database);

	$uname = mysqli_real_escape_string($con,$uname);// helps to prevent sql injection attacks or search failure due to accidental miss spelling
	$passw = mysqli_real_escape_string($con,$passw);// Removes signs as newline single qote double quoute etc.

       //verifies  that connection is succesfull if not display error message
       if (mysqli_connect_errno())
        {
        echo "sorry! couldn't connect to database " . mysqli_connect_error();
        }
	
     //create a myslq query searching for matching password and username
     $result = mysqli_query($con,"SELECT ID, USERNAME, PASSWORD FROM 
     PROJECT.USER_INFO WHERE USERNAME ='$uname' AND PASSWORD='$passw'");

    while ($row = mysqli_fetch_array($result))
    {
     $_SESSION['id']=$row['ID']; // sets session id
    }
     
     $row_count = mysqli_num_rows($result);// count number of rows in result if number of rows = 1 we have matching password and username
     
     //if the search get a hit on the password and username it will contain one row if the database is configured properly i.e. unique username password combinations
     if($row_count==1 and isset($_SESSION['id'])) {
       
	 $_SESSION['username']=$uname;// sets session variable
	 $_SESSION['password']=$passw;
         $_SESSION['condb']=$con;
         
       

        $_SESSION['host'] = $host;
        $_SESSION['user'] = $user;
        $_SESSION['password'] = $password;
        $_SESSION['database'] = $database;


        header("location:home.php");// redirect if correct password is given
     }
     else {
           echo "<h1 name=\"hfail\" id =\"hfail\">"."Tyvärr inloggningen misslyckades!"."</h1>"; // text if password and username has no match

	   echo "<button onclick=\"history.go(-1);\">Tillbaks</button>"; // goes back to login page if pressed
	
	  }
      }
     mysqli_close($con);// close connection
   ?>

 </body>
